<?php
namespace app\v1\logic;

use Think\Db;

class MyFunctions extends \think\Model
{

    /*
     * 验证字段是否已经存在
     * @param $table 要查询的表  $key 字段名  $val 值
     * */
    public function existsSave($table, $key, $val)
    {
        return Db::name($table)->where($key, $val)->find() ? 1 : 0;
    }

    /*
     * 搜索关键字标亮
     * $param  $myList 查询出来的数据  $findTitle 搜索的字符
     *
     * */
    public function editFont($myList, $findTitle)
    {
        foreach ($myList as $key => $val) {
            foreach ($val as $k => $v) {
                if (strstr($v, $findTitle)&&$k!="id") {
                    $myList[$key][$k] = str_replace($findTitle, "<span style='color:red'><strong>$findTitle</strong></span>", $myList[$key][$k]);
                }
            }
        }
        return $myList;
    }

    /*
     * 分页类
     * @param  array $totalRows 总记录
     * @param  array $listRows  每页显示记录数
      @param   array $parameter  分页跳转的参数
     * */
    public function myPage($totalRows, $listRows, $parameter)
    {
        $totalPage = ceil($totalRows / $listRows);//总页数
        $parameter = $parameter < 0 ? 1 : $parameter; //第一页越界显示第一页
        $parameter = $parameter > $totalPage ? $totalPage : $parameter;//最后一页越界显示最后一页
        \think\Session::set("nowPage", $parameter);
        $startRows = $listRows * $parameter - $listRows;//从哪个下标开始
        return array("startRows" => $startRows, "listRows" => $listRows, "totalPage" => $totalPage, "parameter" => $parameter, "totalRows" => $totalRows);
    }

    /*
     * 剪取网页内容
     * */
    public function cut($from, $start, $end, $lt = false, $gt = false)
    {
        $str = explode($start, $from);
        if (isset($str['1']) && $str['1'] != '') {
            $str = explode($end, $str['1']);
            $strs = $str['0'];
        } else {
            $strs = '';
        }
        if ($lt) {
            $strs = $start . $strs;
        }
        if ($gt) {
            $strs .= $end;
        }
        return $strs;
    }

    //获取内容get_contents
    function get_contents($url)
    {
        $curl = curl_init();
        $header = array(
            'User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1 wechatdevtools/0.7.0 MicroMessenger/6.3.9 Language/zh_CN webview/0',
        );
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //  curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
        $data = curl_exec($curl);
        if (curl_errno($curl)) {
            return 'ERROR ' . curl_error($curl);
        }
        curl_close($curl);
        return $data;
    }

    /*
     * 抓取远程图片
     * */

    function getImage($url, $filename)
    {
//下载腾讯，新浪微博等图片
//$url：图片URL
//$filename 文件名
        $header = array("Connection: Keep-Alive", "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Pragma: no-cache", "Accept-Language: zh-Hans-CN,zh-Hans;q=0.8,en-US;q=0.5,en;q=0.3", "User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:29.0) Gecko/20100101 Firefox/29.0");
        $ch = curl_init();
        $v = "";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, $v);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
        $content = curl_exec($ch);
        $curlinfo = curl_getinfo($ch);
        //关闭连接
        curl_close($ch);
        if ($curlinfo['http_code'] == 200) {
            if ($curlinfo['content_type'] == 'image/jpeg') {
                $exf = '.jpg';
            } else if ($curlinfo['content_type'] == 'image/png') {
                $exf = '.png';
            } else if ($curlinfo['content_type'] == 'image/gif') {
                $exf = '.gif';
            }
            //存放图片的路径及图片名称
            //$filename =date("Ymd").uniqid().$exf;
            file_put_contents($filename, $content);
        }
        return $filename;
    }

    /*
     * 数组转换
     * */
    function arr2s($array, $type = 'insert', $exclude = array())
    {
        $sql = '';
        if (count($array) > 0) {
            foreach ($exclude as $exkey) {
                unset($array[$exkey]);//剔除不要的key
            }

            if ('insert' == $type) {
                $keys = array_keys($array);
                $values = array_values($array);
                $col = implode("`, `", $keys);
                $val = implode("', '", $values);
                $sql = "(`$col`) values('$val')";
            } else if ('update' == $type) {
                $tempsql = '';
                $temparr = array();
                foreach ($array as $key => $value) {
                    $tempsql = "'$key' = '$value'";
                    $temparr[] = $tempsql;
                }

                $sql = implode(",", $temparr);
            }
        }
        return $sql;
    }

    /*
     * unicode编码
     * */
    function unicode_encode($name)
    {
        $name = iconv('UTF-8', 'UCS-2', $name);
        $len = strlen($name);
        $str = '';
        for ($i = 0; $i < $len - 1; $i = $i + 2) {
            $c = $name[$i];
            $c2 = $name[$i + 1];
            if (ord($c) > 0) {   //两个字节的文字
                $str .= '\u' . base_convert(ord($c), 10, 16) . str_pad(base_convert(ord($c2), 10, 16), 2, 0, STR_PAD_LEFT);
            } else {
                $str .= $c2;
            }
        }
        return $str;
    }

//将UNICODE编码后的内容进行解码
    function unicode_decode($name)
    {
        //转换编码，将Unicode编码转换成可以浏览的utf-8编码
        $pattern = '/([\w]+)|(\\\u([\w]{4}))/i';
        preg_match_all($pattern, $name, $matches);
        if (!empty($matches)) {
            $name = '';
            for ($j = 0; $j < count($matches[0]); $j++) {
                $str = $matches[0][$j];
                if (strpos($str, '\\u') === 0) {
                    $code = base_convert(substr($str, 2, 2), 16, 10);
                    $code2 = base_convert(substr($str, 4), 16, 10);
                    $c = chr($code) . chr($code2);
                    $c = iconv('UCS-2', 'UTF-8', $c);
                    $name .= $c;
                } else {
                    $name .= $str;
                }
            }
        }
        return $name;
    }

    /*
     * 获取当前时间
     * @param $type=1|Y-m-d    $type=2|Y-m-d H:i:s
     * */
    public function getNowTime($type)
    {
        return $type == 1 ? date("Y-m-d", time()) : date("Y-m-d H:i:s", time());
    }

    /*
     * 分析日期数据
     * */
    public function ipByDayCount($ipArr)
    {
        $resultArr = array("charging" => 0, "chargingMoney" => 0, "uncharging" => 0, "unchargingMoney" => 0, "past" => 0, "pastMoney" => 0, "percentage" => 0, "percentageMoney" => 0
        , "apprentice" => 0, "apprenticeMoney" => 0, "reg" => 0, "regMoney" => 0
        );
        foreach ($ipArr as $key) {

            //计费ip
            $resultArr['charging'] = $key['money'] != 0 && $key['aid'] > 10 ? $key['ip'] : $resultArr['charging'];
            $resultArr['chargingMoney'] = $key['money'] != 0 && $key['aid'] > 10 ? $key['money'] : $resultArr['chargingMoney'];
            //未计费ip
            $resultArr['uncharging'] = $key['money'] == 0 && $key['aid'] > 10 ? $key['ip'] : $resultArr['uncharging'];
            $resultArr['unchargingMoney'] = $key['money'] == 0 && $key['aid'] > 10 ? $key['money'] : $resultArr['unchargingMoney'];
            //签到
            $resultArr['past'] = $key['aid'] == 1 ? $key['ip'] : $resultArr['past'];
            $resultArr['pastMoney'] = $key['aid'] == 1 ? $key['money'] : $resultArr['pastMoney'];
            //提成
            $resultArr['percentage'] = $key['aid'] == 2 ? $key['ip'] : $resultArr['percentage'];
            $resultArr['percentageMoney'] = $key['aid'] == 2 ? $key['money'] : $resultArr['percentageMoney'];
            //收徒
            $resultArr['apprentice'] = $key['aid'] == 3 ? $key['ip'] : $resultArr['apprentice'];
            $resultArr['apprenticeMoney'] = $key['aid'] == 3 ? $key['money'] : $resultArr['apprenticeMoney'];
            //注册
            $resultArr['reg'] = $key['aid'] == 0 ? $key['ip'] : $resultArr['reg'];
            $resultArr['regMoney'] = $key['aid'] == 0 ? $key['money'] : $resultArr['regMoney'];

            $resultArr['day'] = $key['day'];
        }
        $resultArr['bilv'] = number_format(($resultArr['uncharging'] / ($resultArr['charging'] + $resultArr['uncharging'])) * 100, 2);
        unset($ipArr);
        return $resultArr;
    }

    /*
     * 获取用户权限
     * @param  $power_t_list|主分类二维数组  $power_list|子分类二维数组
     * */
    public function getUserPower($power_t_list, $power_list)
    {
        for ($i = 0, $k = 0; $i < count($power_t_list); $i++) {

            for ($j = 0; $j < count($power_list); $j++) {
                if ($power_list[$j]['t_id'] == $power_t_list[$i]['id']) {
                    $power_t_list[$i]['sonType'][$k] = $power_list[$j];
                }
                $k++;
            }
        }
        unset($power_list);//销毁子分类
        return $power_t_list;
    }

    /*
     * 获取图片路径如果平台使用目录下图片进行拼接
     * */
    public function getOtherImg($content, $domain)
    {
        preg_match_all('/<img[^>]*>/i', $content, $match1);
        $imgs = $match1[0];
        $i = 0;
//匹配出图片路径
        foreach ($imgs as $key) {
            preg_match_all("/<img.*src\s*=\s*[\"|\']?\s*([^>\"\'\s]*)/i", $match1[0][$i], $match2);
            $imgUrl[$i] = $match2[1][0];
            $i++;
        }
        $i = 0;
//破解图片
        foreach ($imgs as $img1) {
            //切割内容体插入图片
            $cstr = explode($img1, $content);

            $content = $cstr[0] . "<img style='width:100%' src='$domain$imgUrl[$i]' />" . $cstr[1];
            $i++;
        }
        return $content;
    }

    /*
     * 讲获取的数据id做成拼接成ids(以,号切割)
     *      * */
    public function idExplode($arr){
        $res="";
        foreach($arr as $key){
            $res=$res.",{$key['id']}";
        }
        return substr($res,1);
    }


   public function https_request($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        if (curl_errno($curl)) {return 'ERROR '.curl_error($curl);}
        curl_close($curl);
        return $data;
    }
    /*
     * 获取用户授权信息
     * */
    public  function getWcUserInfo($appid,$appsecret,$code){
        //Get access_token
        //echo "code=".$code;
        $access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
        $access_token_json = $this->https_request($access_token_url);
        // echo $access_token_json;
        $access_token_array = json_decode($access_token_json,true);
        $access_token = $access_token_array['access_token'];
        $openid = $access_token_array['openid'];
        $userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
        $userinfo_json = $this->https_request($userinfo_url);
        //echo $userinfo_json;
        $info= json_decode($userinfo_json,true);
        return $info;

    }
    public  function getWcUserOpenid($appid,$appsecret,$code){
        $access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
        $access_token_json = https_request($access_token_url);
        $access_token_array = json_decode($access_token_json,true);
        $openid = $access_token_array['openid'];
        return $openid;

    }

    /*
 * 请求接口内容
 * @param  $url : 接口名
 * @param $model : 请求方式 默认get
 * @param $arr  : 请求的参数默认为空
 * */
    public function getApiByName($url, $model = "GET", $arr = "", $result = "arr")
    {
        //echo  $url."model:".$model;
        $curl = curl_init();
        $headers = [
            "access_token:" . '$SUPER_USER_ACCESS_TOKEN$'
            , "content-type: application/json"];
        if ($model == "POST") {
            curl_setopt($curl, CURLOPT_URL, $url);//请求链接
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($arr));//请求数据
        } else if ($model == "GET") {
            if (isset($arr['key'])) {

                curl_setopt($curl, CURLOPT_URL, $url . "?" . $arr['key'] . "=" . urlencode($arr['value']));//是否携带参数
                // echo $url . "?" . $arr['key'] . "=" . urlencode($arr['value']);
            } else {
                $arr ? curl_setopt($curl, CURLOPT_URL, $url . "/" . $arr['value']) : curl_setopt($curl, CURLOPT_URL, $url);//是否携带参数
            }
        } else {
            curl_setopt($curl, CURLOPT_URL, $url);//请求链接
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $model);//请求方式
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($arr));//请求数据
        }

        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 0);

        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //设置提交方式

        $data = curl_exec($curl);
        curl_close($curl);
        return  $data ; //判断返回数据还是状态码
    }

    /*
     * 多参数get方式
     * */
    public function getApiByParam($url, $arr, $result = "arr")
    {
        $curl = curl_init();
        $headers = [
            "access_token:" . '$SUPER_USER_ACCESS_TOKEN$'
            , "content-type: application/json"];
        $path = "";//路径
        for ($i = 0; $i < count($arr); $i++) {
            $path = $path . $arr[$i] . "=" . $arr[$i + 1] . "&";
            $i++;
        };
        curl_setopt($curl, CURLOPT_URL, $url . "?" . $path);//是否携带参数
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 0);

        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        curl_close($curl);
        return $data ; //判断返回数据还是状态码
    }

    /*
     * 对象转数组
     * */
    public function objToArr($object){
        $array = null;
        if (is_object($object)) {
            foreach ($object as $key => $value) {
                $array[$key] = $value;
            }
        }
        else {
            $array = $object;
        }
        return $array;
    }
}